/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.chanceit.ssss.fragments;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import net.tsz.afinal.http.AjaxCallBack;

import org.gl.GlobalVariable;
import org.gl.customview.PullToRefreshView;
import org.gl.customview.PullToRefreshView.OnFooterRefreshListener;
import org.gl.customview.PullToRefreshView.OnHeaderRefreshListener;
import org.gl.utils.lg;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.chanceit.ssss.activity.R;
import com.chanceit.ssss.common.ActivityActionName;
import com.chanceit.ssss.common.IntentExtraDataKey;
import com.chanceit.ssss.common.IntentExtraDataKeyValue;
import com.chanceit.ssss.data.DataSources;

public class CarerInShopListFragment extends BaseFragment implements OnItemClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
	OnListFragmentSelectedListener mCallback;
	DataSources ds;
	List<Map<String, Object>> contents = new ArrayList<Map<String, Object>>();
	String[] keys = new String[] { "userName", "carName", "plate", "number",
			"maintainTime" };
	ListView listView;
	protected JSONArray userListJosnAry = new JSONArray();

	// The container Activity must implement this interface so the frag can
	// deliver messages
	public interface OnListFragmentSelectedListener {
		/** Called by HeadlinesFragment when a list item is selected */
		public void onArticleSelected(int position);
	}
	public View view;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {

	view = inflater.inflate(R.layout.order_carer_list, container, false);
	ds = new DataSources();
	
	initData(null);
	for (int i = 0; i < 10; i++) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put(keys[0], "name");
		map.put(keys[1], "Test Title");
		map.put(keys[2], "Test Content");
		map.put(keys[3], "Test Content");
		map.put(keys[4], "Test Content");
		contents.add(map);
	}
	listView = (ListView) view.findViewById(R.id.order_carer_lv);
	listView.setOnItemClickListener(this);
//	 adapter = new SimpleAdapter(getActivity(),
//			(List<Map<String, Object>>) contents, R.layout.list_item_carer,
//			keys, new int[] { R.id.textView1, R.id.textView2,
//					R.id.textView3, R.id.textView4, R.id.textView5 });
//	listView.setAdapter(adapter);
	mPullToRefreshView = (PullToRefreshView) (view
			.findViewById(R.id.main_pull_refresh_view));
	mPullToRefreshView.setOnHeaderRefreshListener(this);
	mPullToRefreshView.setOnFooterRefreshListener(this);
	return view;
}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
	}
	int page;
	PullToRefreshView mPullToRefreshView;
	SimpleAdapter adapter;
	@Override
	public void onFooterRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page ++;
				initData(page);
//				mPullToRefreshView.onFooterRefreshComplete();
			}
		}, 1000);
	}
	@Override
	public void onHeaderRefresh(PullToRefreshView view) {
		mPullToRefreshView.postDelayed(new Runnable() {

			@Override
			public void run() {
				page = 1;
				initData(null);
				// 设置更新时间
				// mPullToRefreshView.onHeaderRefreshComplete("最近更新:01-23 12:01");
				mPullToRefreshView.onHeaderRefreshComplete();
			}
		}, 1000);

	}
	private void initData(Integer _page) {
		ds.getInshopCarer(_page,new AjaxCallBack<String>() {
			public void onLoading(long count, long current) {
			}

			public void onSuccess(String t) {
				lg.i(TAG, t);
				try {
					JSONArray temp = new JSONArray(t);
					contents.removeAll(contents);
					if (page<=1) {//如果当前页码为<=1 说明是第一次加载 清楚以前的旧数据
						userListJosnAry = null;
						userListJosnAry=temp;
					}else{//否则就是加载更多的分页数据,把新的数据添加到集合中
						for (int i = 0; i < temp.length(); i++) {
							userListJosnAry.put(temp.opt(i));
						}
					}
					int count = userListJosnAry.length();
					for (int i = 0; i < count; i++) {
						Map<String, Object> map = new HashMap<String, Object>();
						JSONObject temp2 = userListJosnAry.getJSONObject(i);
						for (String key : keys) {
							Object o = temp2.opt(key);
							if (o == null||o.toString().length()<=0) {
								o = "";
							}
							map.put(key, o.toString());
						}
						contents.add(map);
					}
					SimpleAdapter adapter = new SimpleAdapter(context,
							(List<Map<String, Object>>) contents,
							R.layout.list_item_carer, keys, new int[] {
									R.id.textView1, R.id.textView2,
									R.id.textView3, R.id.textView4,
									R.id.textView5 });
					setListAdapter(adapter);
				} catch (JSONException e) {
					e.printStackTrace();
					page--;
				}

			}
		});

	}
	private void setListAdapter(SimpleAdapter adapter) {
	listView.setAdapter(adapter);
		
	}
	@Override
	public void onStart() {
		super.onStart();

		// When in two-pane layout, set the listview to highlight the selected
		// list item
		// (We do this during onStart because at the point the listview is
		// available.)
		if (getFragmentManager().findFragmentById(R.id.article_fragment) != null) {
			listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
		}
	}

	@Override
	public void onAttach(Activity activity) {
		super.onAttach(activity);

		// This makes sure that the container activity has implemented
		// the callback interface. If not, it throws an exception.
		try {
			mCallback = (OnListFragmentSelectedListener) activity;
		} catch (ClassCastException e) {
			lg.e(TAG, "activity not cast to OnListFragmentSelectedListener");
		}
	}


	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
		// Set the item as checked to be highlighted when in two-pane layout
		listView.setItemChecked(position, true);
		try {
			IntentExtraDataKeyValue.updateUserInfoToIntent(userListJosnAry.getJSONObject(position).toString());
		} catch (JSONException e) {
			e.printStackTrace();
		}catch(NullPointerException e){
			e.printStackTrace();
			Toast.makeText(getActivity(), "null user&plate", Toast.LENGTH_SHORT).show();
		}
		// Notify the parent activity of selected item
//		mCallback.onArticleSelected(position);
		getActivity().startActivityForResult(
				GlobalVariable.getGlobalInstance().intent
						.setAction(ActivityActionName.CARER),
				IntentExtraDataKey.ACTIVITY_QUESTCODE_UPDATECARERINFO);
	}
	@Override
	public void receiveMessage(Object message) {
		// TODO Auto-generated method stub
		super.receiveMessage(message);
		initData(null);
	}
}